package models

import (
	"math/rand"
	"time"

	"github.com/astaxie/beego"
)

const (
	USERMODE_INIT = iota // 模式初始化
	USERMODE_SPIT        // 吐分模式
	USERMODE_EAT         // 吃分模式
)

const (
	USERGUESS_INIT  = iota // 用户猜数 初始化
	USERGUESS_BIG          // 大
	USERGUESS_SMALL        // 小
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

func test大小中() {
	var arr [3]int
	r := 0
	for i := 0; i < 10000; i++ {
		r = GuessBigSmall(USERMODE_SPIT, USERGUESS_BIG)
		if r < 7 {
			arr[0]++
		} else if r > 7 {
			arr[2]++
		} else {
			arr[1]++
		}
	}
	beego.Warning("小", arr[0])
	beego.Warning("中", arr[1])
	beego.Warning("大", arr[2])
}

func test水果() {
	var val map[string]uint32 = make(map[string]uint32)
	val["葡萄"] = 888
	val["橘子"] = 888
	val["木瓜"] = 888
	val["柚子"] = 888
	val["柚子2"] = 888
	val["柚子3"] = 888
	val["柚子4"] = 888
	val["柚子5"] = 888
	val["柚子6"] = 888
	val["柚子7"] = 888
	val["柚子8"] = 888

	total := make(map[string]uint32)

	v := ""
	s := time.Now()
	for i := 0; i < 1000000; i++ {
		v = GetProbability(val)
		total[v] = total[v] + 1
	}
	beego.Error(time.Now().Sub(s))
	beego.Critical("总成绩：", total)
}

/*
	mode USERMODE_SPIT 	吐分模式
	mode USERMODE_EAT	吃分模式

	val	USERGUESS_SMALL	小
	val	USERGUESS_BIG	大

	result 中奖号码
	result -1 传参错误
*/
func GuessBigSmall(mode int, val int) (result int) {
	f := 0
	SystemParamenterSync.RLock()
	if mode == USERMODE_SPIT {
		f = SystemParamenter.Patternwin0
	} else if mode == USERMODE_EAT {
		f = SystemParamenter.Patternwin1
	}
	SystemParamenterSync.RUnlock()
	if f == 0 {
		return -1
	}
	s := f + 5
	luck := rand.Intn(100) + 1
	if luck <= f {
		result = rand.Intn(6) //0-5
		if val == USERGUESS_BIG {
			result += 8
		} else if val == USERGUESS_SMALL {
			result += 1
		}
		return
	} else if luck <= s {
		return 7
	}
	result = rand.Intn(6) //0-5
	if val == USERGUESS_BIG {
		result += 1
	} else if val == USERGUESS_SMALL {
		result += 8
	}
	return
}

/*
	m["名称"] = 概率 * 10000
	return "" ---参数错误
	return "未中"
	return "中奖名称"
*/
func GetProbability(m map[string]uint32) (result string) {
	var sum uint32
	flag := make(map[string]int)
	i := 1
	for n, v := range m {
		sum += v
		flag[n] = i
		i++
	}
	if sum == 0 || sum > 10000 {
		beego.Error("参数错误！", sum)
		return ""
	}

	var arr [10000]int8
	f := 0
	for n, v := range m {
		tmp_flag := flag[n]
		for i := uint32(0); i < v; i++ {
			arr[f] = int8(tmp_flag)
			f++
		}
	}

	f = int(arr[rand.Intn(int(10000))])
	for n, v := range flag {
		if v == f {
			return n
		}
	}
	return "未中"

}

/*
	判断本次是否为特殊奖励
*/
func IsSpecialChance() bool {
	SystemParamenterSync.RLock()
	special_num := int(SystemParamenter.SpecialChance * 10)
	SystemParamenterSync.RUnlock()

	luck := rand.Intn(1000) + 1
	if luck <= special_num {
		return true
	}
	return false
}
